<template>
  <div class="topic-page">
    <ylheader :leftsvg="true" :title="'话题'" :rightsvg="true" @search="topicsearch"></ylheader>
    <div class="menuWrap" ref="menuWrap" style="height:0.89rem">
      <ul class="menuWrap_u" :style="{width:allclasswidth+'rem'}">
        <li>
          <a href="javascript:;" @click="selectallclass()" :class="{active:chooseclassindex==-1}">全部</a>
        </li>
        <li v-for="(items,index) in allclasslist" :key="index">
          <a @click="selectotherclass(index,items.className)" :class="{active:chooseclassindex==index}">{{items.className}}</a>
        </li>
      </ul>
    </div>
    <div class="loadmore-container" ref="topiclistWrapper">
      <div class="loadmore-ul">
        <div class="topic-hd">
          <div class="topic-inner">
            <span class="topic-btn right-line" :class="{active:isnewactive}" @click="selectnew">最新</span>
            <span class="topic-btn" :class="{active:!isnewactive}" @click="selecthot">最热</span>
          </div>
        </div>
        <div class="shuoshuo-new" v-if="listnodata">
          <span class="yl-2kong nosvg">
            <span class="path1">
              <span class="path2">
                <span class="path3">
                  <span class="path4">
                    <span class="path5">
                      <span class="path6">
                        <span class="path7">
                          <span class="path8">
                            <span class="path9"></span>
                          </span>
                        </span>
                      </span>
                    </span>
                  </span>
                </span>
              </span>
            </span>
          </span>
          <span class="no-text">还没有相关内容哦，快去跟大家互动吧！</span>
        </div>
        <ul class="topiclistul">
          <li v-for="(items,index) in list"  :key="index">
              <hottopicnew @click.native="totopicdetail(items)" :topicimg="items.topicPicture" :abbreviations="items.abbreviations" :followNumber="items.followNumber" :title="items.title" :topictype="items.isShow">
              </hottopicnew>
          </li>
        </ul>
        <p style="padding-bottom:10px;"></p>
      </div> 
    </div>
    <div class="submission-topic" @click="$router.push({path:'submission'})" v-if="pictureUrl"><img :src="pictureUrl" alt=""></div>
  </div>
</template>
<script>
import BScroll from 'better-scroll'
import hottopicnew from "src/components/topic/hot-topic-list.vue";
import ylheader from "src/components/yl-header.vue";
import api from "src/api/index";
import { mapState, mapMutations } from "vuex";
import {Indicator } from "mint-ui";
export default {
  name:"topic",
  data() {
    return {
      type: 0,//0最新 1最热
      className: "",//分类名
      selected: "",
      list: [],
      topicId: "",
      topicType: "",
      hasmore: "",
      page: 1,
      totalPage: 0,
      myid: "",
      pageone: 1,
      pagetwo: 1,
      loadmore: false,
      is_r: false,
      scrollMode: false,
      swipeable: true,
      allclasslist: [],
      allclasslistindex: "1",
      lastactiveindex: -1,//记录上一个点击的tab
      isallclassactive: true,//是否选中全部tab
      isnewactive: true,
      chooseclassindex: -1,//默认选中tab
      listnodata:false,//判断是否有数据
      scrollTop: 0,
      allclasswidth:0,
      pictureUrl:""//投稿入口图片
    }
  },
  watch: {
    selected(val, oldval) {
      this.changetopicstatus(val);
      this.myid = val;
    }
  },
  components: {
    hottopicnew,
    ylheader,
  },
  computed: {
    ...mapState(["topicstatus","searchresultselected"])
  },
  beforeRouteEnter: (to, from, next) => {
    next(vm => {
      if (from.path === '/') {
        setTimeout(() => {
          vm.$bus.$emit('scrollToTop')
        }, 150);
      }
    })
  },
  mounted() {
    this.init();
    },
  methods: {
    ...mapMutations(["changetopicstatus","changesearchresultselected"]),
    init(){
      this.getallclass()
      .then(res => {
          this.getList()
      }).then(data=>{
        this.initScroll();
      })
      .then(data => {
        this.queryArticlesEnter();
        this.$nextTick(() => {
          if (!!this.myscroll) this.myscroll.refresh();
        });
        let loadmore = document.getElementsByClassName("loadmore-ul");
        if ("topiclist2detail" == localStorage.turnCount) {
          if (loadmore.length > 0) {
            setTimeout(() => {
              loadmore[0].style.transform = localStorage.turnBackTopic;
            }, 0);
          }
          localStorage.turnCount = "";
        } 
      })
      .then(res => {
        setTimeout(()=>{
          if (!this.scroll) {
            this.scroll = new BScroll(this.$refs.menuWrap, {
              scrollX: true,
              click: true
            })
          } else {
            this.scroll.refresh()
          }
        },20)
      });
    },
    initScroll() {
      let p = new Promise((resolve, reject) => {
        let topiclistWrapper = this.$refs.topiclistWrapper;
        localStorage.tempPageHeight = document.getElementsByClassName(
          "loadmore-ul"
        )[0].scrollHeight;
        let _this = this;
        this.$nextTick(() => {
          _this.myscroll = new iScroll(topiclistWrapper, {
            preventDefault: false,
            onScrollMove: function() {
              if ((this.y <= (this.wrapperH - this.scroller.clientHeight-50))&& _this.is_r == false) {
                _this.is_r = true;
                if(_this.page<_this.totalPage){
                  _this.page++;
                  _this.getList();  
                }
              }
            },
            onScrollEnd: function() { },
            onScrollStart: function() {
              if (
                localStorage.tempPageHeight !=
                document.getElementsByClassName("loadmore-ul")[0].scrollHeight
              ) {
                this.refresh();
                localStorage.tempPageHeight = document.getElementsByClassName(
                  "loadmore-ul"
                )[0].scrollHeight;
              }
            }
          });
          resolve("初始化scroll");
        });
      });
      return p;
    },
    //选择全部
    selectallclass() {
      localStorage.turnCount = "";
      this.chooseclassindex = -1;
      this.className = "";
      this.page = 1;
      this.getList();
      this.myscroll.scrollTo(0,0)
    },
    //选择除了全部之外的tab
    selectotherclass(index, className) {
      localStorage.turnCount = "";
      this.chooseclassindex = index;
      this.className = className;
      this.page = 1;
      this.getList();
      this.myscroll.scrollTo(0,0)
    },
    //点击最新
    selectnew() {
      localStorage.turnCount = "";
      this.isnewactive = true;
      this.page = 1;
      this.type = 0;
      this.getList();
       this.myscroll.scrollTo(0,0)
    },
    //点击最热
    selecthot() {
      localStorage.turnCount = "";
      this.isnewactive = false;
      this.page = 1;
      this.type = 1;
      this.is_r = false
      this.getList();
      this.myscroll.scrollTo(0,0)
    },
    getList() {
      let p = new Promise((resolve, reject) => {
       
          Indicator.open("加载中...");
          const data = {
            page: this.page,
            limit: 10,
            type: this.type,
            className: this.className
          }
          api.Querytopic(data).then(res => {
            Indicator.close();
            if (res.success) {
              this.totalPage = res.data.totalPage
              this.list = this.is_r
                 ? [...this.list, ...res.data.list]
                 : res.data.list;
              if(this.page<res.data.totalPage){
                  this.is_r=false;
              }
              if(this.list.length==0){
                  this.listnodata = true;
              } else{
                 this.listnodata = false;
              }
              if(this.myscroll){
                this.$nextTick(() => {
                  this.myscroll.refresh();
                });
              } 
              let topiclistObj = JSON.stringify({
                list:this.list,
                page: this.page,
                totalPage: this.totalPage,
                isnewactive:this.isnewactive,
              });
              localStorage.topiclistStorage = topiclistObj;
              resolve("获取话题列表....");
            }
            resolve("获取分类内容....");
          })
      
      });
      return p;
    },

    //获取全部分类
    getallclass() {
      let p = new Promise((resolve, reject) => {
        api.Queryalltopicclass().then(res => {
          this.allclasslist = res;
          this.allclasswidth=0;
          _each(this.allclasslist, (v, i) => {
            this.allclasswidth+=(v.className.length)*15+30;
            v.isactive = false
          })
          resolve("获取所有分类....");
        })
      })
      return p;
    },
    totopicdetail(items) {
      const addclick = {
        id: items.topicId,
        type: 1
      };
      this.$util.saveclicknum(addclick);
      localStorage.turnCount = "topiclist2detail";
      this.getTransformState();
      this.changetopicstatus(this.chooseclassindex)
      this.$router.push({
        path: "/topicdetail",
        query: { topicId: items.topicId, activeId: items.activityId,token:localStorage.getItem("token")}
      });
    },
    topicsearch() {
      this.changesearchresultselected(0);
      this.$router.push({ path: "/search", query: { type: "1" } });
    },
    //获取跳转前的位置
    getTransformState() {
      let loadmore = document.getElementsByClassName("loadmore-ul");
      if (loadmore.length > 0) {
        localStorage.turnBackTopic = loadmore[0].style.transform;
      }
    },
    queryArticlesEnter(){
      api.queryArticlesEnter().then(res=>{
        if(res.code==0){
          if(res.data){
            this.pictureUrl = res.data.pictureUrl
          }
        }else{
          this.$toast(res.msg)
        }
      })
    }
  },
  destroyed() {
    if (this.myscroll) {
      this.myscroll.destroy();
      this.myscroll = null;
    }
  }
};
</script>
<style lang="less">
.topic-title-mtnav {
  border-bottom: 1px solid #e6e6e6;
  justify-content: space-between;
  height: 0.9rem;
  padding: 0 0.94rem;
  .mint-tab-item {
    flex: inherit;
  }
  .mint-tab-item-label {
    color: #333333;
    font-size: 0.3rem;
    font-family: "PingFangSC Regular";
  }
  .mint-tab-item.is-selected {
    border-bottom: 0.04rem solid #a0c0d8;
    margin-bottom: 0;
    font-family: "PingFangSC Regular";
  }
}

.topic-mtnav {
  border-bottom: 1px solid #e6e6e6;
  padding: 0 0.94rem;
  justify-content: space-between;
  height: 0.9rem;

  .mint-tab-item {
    flex: inherit;
  }
  .mint-tab-item-label {
    color: #333333;
    font-size: 0.1rem;
    font-family: "PingFangSC Regular";
  }
  .mint-tab-item.is-selected {
    border-bottom: 0.04rem solid #a0c0d8;
    margin-bottom: 0;
    font-family: "PingFangSC Regular";
  }
}

.all-hot-title {
  height: 0.88rem;
  background-color: white;
  padding-left: 0.3rem;
  line-height: 0.88rem;
  font-size: 0.28rem;
  font-family: "PingFangSC Regular";
  color: #3a3a3a;
}
.topiclistul{
  margin-top: -0.2rem;
}
.submission-topic{
  position: fixed;
  bottom: 0.5rem;
  right: 0.3rem;
  img{
    width:1.1rem;
    height: 1.1rem;
  }
}
</style>
<style scoped>
.loadmore-container {
  height: 95vh;
  overflow: auto !important;
  margin: 0 auto;
}

.loadmore-ul {
  padding-bottom: 1.2rem;
  list-style: none;
}

</style>
<style scoped>
html,
body,
.topic-page {
  height: 100%;
}
</style>
